<template>
  <el-dialog v-el-drag-dialog width="1000px" :title="formName" :visible="show" @update:visible="updateShow">
    <el-radio-group v-model="listQuery.PlatFormType" @change="getMenuList(), getRoleMenuList()">
      <el-radio-button v-if="UserRole" label="PC">电脑端</el-radio-button>
      <el-radio-button label="APP">移动端</el-radio-button>
    </el-radio-group>

    <el-row style="margin-top: 15px">
      <el-col :span="8" class="menuList">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        <el-card class="menuTree">
          <el-tree class="filter-tree" show-checkbox v-loading="treeDataLoading" :data="treeData" :checkStrictly="true" node-key="Id" highlight-current :props="defaultProps" :filter-node-method="filterNode" :expand-on-click-node="false" ref="menuTree" @node-click="getNodeData" @check="nodeCheck" :default-expanded-keys="menuNodeKey" :current-node-key="menuNodeKeyStr" default-expand-all>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-table v-if="listQuery.PlatFormType == 'PC'" ref="elementTable" v-loading="listLoading" :data="buttonlist" border stripe fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="按钮编码">
            <template slot-scope="{ row }">
              <span>{{ row.BtnCode }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="按钮作用">
            <template slot-scope="{ row }">
              <span>{{ row.BtnName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="该用户权限">
            <template slot-scope="{ row }">
              <el-switch v-model="row.isUserRole" active-color="#13ce66" inactive-color="#ececec">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>

        <el-button v-if="listQuery.PlatFormType == 'PC'" class="float-right" type="success" @click="saveBtnlist">
          保存
        </el-button>

      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="updateShow(false)"> 取消 </el-button>
      <el-button type="primary" @click="save"> 保存 </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import { deepClone } from '@/utils'
  import { getList, save } from '@/api/system/menu'
  import { getUserRoleAuthority, saveUserRoleAuthority } from '@/api/system/user-role'
  import { mapState } from 'vuex'
  import elementIcons from '@/views/icons/element-icons'
  import systemButton from '@/views/System/systemButton'
  import { getSystemButton, GetBtnAuthList, SaveBtnAuth } from '@/api/system/system-button'
  export default {
    components: { systemButton },
    props: {
      show: {
        type: Boolean,
        default() {
          return false
        }
      },
      isAddChild: {
        type: Boolean,
        default() {
          return false
        }
      },
      formData: {
        type: Object,
        default() {
          return {}
        }
      },
      platFormType: {
        default() {
          return 'PC'
        }
      }
    },
    data() {
      return {
        UserRole: true,
        RoleMenuList: [],
        appList: [],
        form: {},
        formTmpl: {
          MenuIcon: '',
          menuParentName: '',
          MenuParentId: '00000000-0000-0000-0000-000000000000',
          PlatFormType: 'PC',
          MenuType: true
        },
        rules: {
          MenuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
          MenuPath: [{ required: true, message: '请输入菜单链接', trigger: 'blur' }],
          // Remark: [{ required: true, message: '请输入菜单标识', trigger: 'blur' }],
        },
        listQuery: {
          PlatFormType: 'APP',
          MenuName: "", //页面名称
          IsPaging: false, //是否分页
          SortName: "MenuSort", //排序栏位
          SortType: true //排序类型｛True：正序；Flase：反序｝
        },
        filterText: '',
        defaultProps: {
          children: 'ChildList',
          label: 'MenuName'
        },
        currentMenuId: '',
        treeData: [
          {
            Id: undefined,
            MenuName: '一级目录'
          }
        ],
        treeDataLoading: true,
        menuNodeKey: [],
        menuNodeKeyStr: '',
        elementIcons: elementIcons,
        listLoading: false,
        buttonlist: []
      }
    },
    computed: {
      formName() {
        if (this.form.Id) {
          return '编辑'
        }
        return '菜单设置'
      },
      // ...mapState({
      //   sRoleId: state => state.user.userInfo.RoleId,
      // }),
    },
    watch: {
      'listQuery.PlatFormType': {
        deep: true,
        immediate: true,
        handler(val) {
          // if (this.$refs['dataForm']) {
          //   this.$refs['dataForm'].clearValidate()
          // }
          if (val == 'PC') {
            this.appList = []
          }
        }
      },
      formData: {
        deep: true,
        immediate: true,
        handler(val) {
          // if (this.$refs['dataForm']) {
          //   this.$refs['dataForm'].clearValidate()
          // }
          if (val.Institution || val.SystemRole) {
            this.listQuery.PlatFormType = 'PC'
            this.UserRole = true
            console.log(this.listQuery.PlatFormType)
          } else {
            this.listQuery.PlatFormType = 'APP'
            this.UserRole = false
          }
          this.appList = []
          this.roleId = val.Id
          if (this.roleId) {
            this.filterText = ''
            this.getMenuList()
            this.getRoleMenuList()
          }
        }
      },
      filterText: {
        handler(val) {
          this.$refs.menuTree.filter(val)
        }
      }
    },
    methods: {
      updateShow(val) {
        this.$emit('update:show', val)
      },
      getSystemButtonList(MenuId) {
        return new Promise(next => {
          this.listLoading = true
          let obj = {
            "MenuId": MenuId,
            "IsPaging": false, //是否分页
          }
          getSystemButton(obj).then(res => {
            this.listLoading = false
            // this.buttonlist = res.Data
            next({ MenuId, 'sdata': res.Data })
          })
        })
      },
      checkUserButtonRole(data) {
        let { MenuId, sdata } = data
        this.MenuId = MenuId
        return new Promise(next => {
          let obj = {
            "MenuId": MenuId, //菜单Id
            "RoleId": this.roleId, //角色Id
            "IsPaging": false,
          }
          GetBtnAuthList(obj).then(res => {
            sdata.forEach(item => {
              item.isUserRole = false
              for (let cell of res.Data) {
                if (cell.BtnId == item.Id) {
                  item.isUserRole = cell.IsActive
                }
              }
            })
            this.buttonlist = sdata
          })
        })
      },
      async dealButtonList(MenuId) {
        let data = await this.getSystemButtonList(MenuId)
        await this.checkUserButtonRole(data)
      },
      afterSave() {
        this.$notify({
          title: '操作成功',
          message: 'success',
          type: 'success',
          duration: 2000
        })
        this.updateShow(false)
        this.$emit('finish')
      },
      save() {
        const keys = this.$refs.menuTree.getCheckedKeys()
        if (!keys.length) {
          return
        }
        const formData = keys.map(item => {
          return {
            RoleId: this.roleId,
            MenuId: item,
            PlatForm: this.listQuery.PlatFormType
          }
        })

        saveUserRoleAuthority(formData).then(() => {
          this.afterSave()
        })

      },
      saveBtnlist() {
        console.log(this.buttonlist)
        let list = this.buttonlist.map(item => {
          return { RoleId: this.roleId, MenuId: this.MenuId, BtnId: item.Id, IsActive: item.isUserRole }
        })
        SaveBtnAuth(list).then(res => {
          this.$notify({
            title: '保存按钮权限成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
        })
      },
      getMenuList() {
        console.log(this.listQuery.PlatFormType)
        let that = this;
        that.treeDataLoading = true
        that.treeData = []
        const param = {
          PlatFormType: that.platFormType,
          ...that.listQuery
        }
        getList(param).then((res) => {
          that.treeData = that.treeData.concat(res.Data)
          that.treeDataLoading = false
          this.dealButtonList(that.treeData[0].Id)
          console.log(that.treeData)
        }).catch(err => {
          that.treeData = []
        })
      },
      async getRoleMenuList() {
        const { Data, Code } = await getUserRoleAuthority({ RoleId: this.roleId, PlatForm: this.listQuery.PlatFormType })

        this.$refs.menuTree.setCheckedKeys(Data.map(item => item.MenuId))

      },
      filterNode(value, data) {
        if (value === '') return true;
        return data.MenuName.indexOf(value) !== -1;
      },
      getNodeData(data) {
        console.log(data)
        this.form.menuParentId = data.Id
        this.form.menuParentName = data.MenuName
        this.dealButtonList(data.Id)

      },
      generateElementIconCode(symbol) {
        return `<i class="el-icon-${symbol}" />`
      },
      nodeCheck(data, stateNodes) {
        // console.log(this.$refs.menuTree.getNode(data))
        let node = this.$refs.menuTree.getNode(data)
        this.childNodesChange(node, node.checked);
        if (node.checked) {
          this.parentNodesChange(node);
        }

      },
      childNodesChange(node, checked) {
        let len = node.childNodes.length;
        for (let i = 0; i < len; i++) {
          node.childNodes[i].checked = checked;
          this.childNodesChange(node.childNodes[i], checked);
        }
      },
      parentNodesChange(node) {
        if (node.parent) {
          // for(let key in node){
          //   if(key == "parent"){
          //     node[key].checked = true;
          node.parent.checked = true;
          this.parentNodesChange(node.parent);
          // this.parentNodesChange(node[key]);
          //   }
          // }
        }
      },
      clearEmptyChild(arr, key) {
        for (let i in arr) {
          if (!arr[i][key] || !arr[i][key].length) {
            delete arr[i][key]
          } else {
            this.clearEmptyChild(arr[i][key])
          }
        }
        return arr
      },

    }
  }
</script>
<style lang="scss" scoped>
  .float-right {
    float: right;
    margin-top: 20px;
  }
  .icon-list {
    width: 300px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    max-height: 300px;
    overflow-y: scroll;
    .icon-item {
      font-size: 30px;
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      &:hover {
        color: blue;
        cursor: pointer;
        background: #dddddd;
        border-radius: 6px;
      }
    }
  }
</style>
